<template>
    <div class="stuPage">
        <div class="toolsBar">
            <a-icon type="home"　theme="twoTone" two-tone-color="#8e96cc"/>
            <h3>DormSpace</h3>
            
            <a-dropdown placement="bottomRight">
                <a-button ghost style="padding:0;border:0;margin-top:6px;margin-left:160px">
                    <a-badge dot><a-avatar style="backgroundColor:#94b6fa" icon="user"/></a-badge>
                </a-button>
                <a-menu slot="overlay" theme="dark">
                  <a-menu-item>
                    <nuxt-link to="/stuPage/stuLogin">{{loginName}}</nuxt-link>
                  </a-menu-item>
                </a-menu>
            </a-dropdown>
        </div>
        <div class="dataPart" >
            <div class="myCard" id="tempAndHumi" style="width:98%">
                <div style="font-size:20px;color:white;padding:10px;margin-top:19px">寝<br>室<br>温<br>湿<br>度</div>
                <div id="humiContainer" style="height:100%;width:50%;float:left;margin:0"></div>
                <div id="tempContainer" style="height:100%;width:48%;float:left;margin:0;padding-top:10px;padding-bottom:10px"></div>
            </div>
            <div class="myCard" id="dormInfo" style="display:block">
              <div id="title">
                <h2>个人信息</h2>
              </div>
              <div>
                <p><h3>寝室号:</h3><h4>{{myInfo.roomId}}</h4></p>
                <p><h3>学号:</h3><h4>{{myInfo.studentId}}</h4></p>
                <p><h3>姓名:</h3><h4>{{myInfo.name}}</h4></p>
                <p><h3>手机号:</h3><h4>{{myInfo.phone}}</h4></p>
              </div>
            </div>
            <div class="myCard" id="buttonPart" style="display:block">
              <div v-if="myInfo.isChecked==false">
                <a-button type="primary" class="aButton">打卡</a-button>
              </div>
              <div v-else>
                <h3>{{myInfo.position}}</h3>
              </div> 
                <a-button type="primary" class="aButton">查看监控</a-button>
            </div>
            <div class="myCard" id="messagePart">
                 <div class="talkPart">
                    <div class="sentencePart" ref="sentencePart">
                    <table>
                        <span v-for="(sentence,index) in sentenceList" :key="index" style="width:100%;display:block">
                            <tr v-if="sentence.admin==false">
                                <td style="width:50%"></td>
                                <td><h1 class="type1">{{sentence.content}}</h1></td>
                            </tr>
                            <tr v-else>
                                <td><h1 class="type2">{{sentence.content}}</h1></td>
                                <td style="width:50%"></td>
                            </tr>
                        </span>
                    </table>
                    </div>
                    <div class="sendPart">
                        <div style="width:169px;">
                            <a-form-item style="width:150px;margin:0">
                                <a-input  :value="value" @change="handleChange" style="resize:none;width:150px;margin-left:8px;" @keydown.enter.native.prevent="handleSubmit"/>
                            </a-form-item>
                            <a-form-item>
                                <a-button html-type="submit" :loading="submitting" type="primary" @click="handleSubmit" class="aButton">
                                发送
                                </a-button>
                            </a-form-item>
                        </div>
                    </div>
                </div>
            </div>
            <div class="myCard" id="waterPart" style="display:block;">
                <div v-if="dormInfo.isWaterBoiled==false">
                    <h3>
                        未加热状态 <a-badge status="processing" color="#2db7f5"/>
                    </h3>
                    
                </div>
                <div v-else>
                    <h3>
                        加热状态
                    </h3>
                    <a-badge status="processing" color="#f50"/>
                </div>
                <a-button type="primary" class="aButton">加热</a-button>
            </div>
        </div>
    </div>
</template>

<script>
import { Liquid, measureTextWidth, Bullet } from '@antv/g2plot'
import moment from 'moment'
import {mapActions,mapState,mapMutations} from 'vuex'
export default {
     computed:{
      ...mapState({
        talkUpdate: 'talkUpdate',
        account:state=> state.account.account,
        signIn: state => state.account.signIn
      })
    },
    layout: "stuLayout",
    data() {
      return {
        loginName:'登录',
        collapsed: false,
        comments: [],
        submitting: false,
        value: '',
        moment,
        sentenceList:[
          {
            'admin':false,
            'content':'fuck'
          },
          {
            'admin':false,
            'content':'fuck'
          },
         {
            'admin':true,
            'content':'fuck'
          }
        ],
        myInfo:
        {
          'studentId':'8209190507',
          'roomId':111,
          'name':'夏家豪',
          'status':'请假',
          'isChecked':false,
          'position':'沈阳大街好果汁店',
          'phone':'17873161949'
        },
        dormInfo:
        {
          'roomId':111,
          'leaderId':'8209190507',
          'temperature':40.0,
          'humility':0.9,
          'status':'正常',
          'memo':'nothing',
          'isDoorOpened':false,
          'isWaterBoiled':false
        },
        display: 'none'
      };
    },
    props: {
      showCard: {
        type: Boolean,
        default: false
      }
    },
    watch:{
    talkUpdate:{
      immediate:true,
      handler(newVal){
        if(newVal)
        {
          this.updateTalkList()
        }
      }
    },
    showCard: {
      immediate: true,
      handler(newVal) {
        let self = this
        if(newVal === false) {
          setTimeout(() => {
            self.display = 'none'
          }, 300)
        }
        else {
          self.display = 'block'
        }
      }
    }
    },
    methods:{
      ...mapActions({
        getTalkList:'talk/getTalkList',
        insertSentence:'talk/insertSentence',
      }),
      ...mapMutations({
        finishUpdate: 'finishUpdate'
      }),
        humiPaint(){
            const liquidPlot = new Liquid(document.getElementById('humiContainer'), {
            percent: 0.0,
            statistic: {
              title: {
                formatter: () => '湿度',
                style: ({ percent }) => ({
                  fill: 'white',
                }),
              },
              content: {
                style: ({ percent }) => ({
                  fontSize: 60,
                  lineHeight: 1,
                  fill: 'white' ,
                }),
                customHtml: (container, view, { percent }) => {
                  const { width, height } = container.getBoundingClientRect();
                  const d = Math.sqrt(Math.pow(width / 2, 2) + Math.pow(height / 2, 2));
                  const text = percent>0.3? percent<0.8? `${(percent * 100).toFixed(0)}%`: `${(percent * 100).toFixed(0)}%过高!`:`${(percent * 100).toFixed(0)}%过低!`;
                  const textWidth = measureTextWidth(text, { fontSize: 60 });
                  const scale = Math.min(d / textWidth, 1);
                  return `<div style="width:${d}px;display:flex;align-items:center;justify-content:center;font-size:${scale}em;line-height:${
                    scale <= 1 ? 1 : 'inherit'
                  }">${text}</div>`;
                },
              },
            },
            liquidStyle: ({ percent }) => {
              return {
                fill: percent > 0.3 ? percent < 0.8 ? '#5bf984' : '#ff5662' : '#FAAD14',
                stroke: percent > 0.3 ? percent < 0.8 ? '#5bf984' : '#ff5662' : '#FAAD14',
              };
            },
            color: () => '#5bf984',
            });
            liquidPlot.render();

            let data = this.dormInfo.humility;
            const interval = setInterval(() => {
                data = data;
                liquidPlot.changeData(data);
            }, 500);
        },
        tempPaint(){
            let temp= this.dormInfo.temperature;
            const data = [
              {
                title: '室内温度',
                ranges: [0,50],
                measures: [temp],
                target: [18,24],
              },
            ];
            
            // @TODO 差一张垂直方向的缩略图
            const bulletPlot = new Bullet('tempContainer', {
              data,
              measureField: 'measures',
              rangeField: 'ranges',
              targetField: 'target',
              xField: 'title',
              color: {
                range: '#f0efff',
                measure: temp>=18?temp<=24?'#5bf984':'#ff5662':'#2476ff',
                target: '#e4d92c',
              },
              xAxis: {
                line: null,
              },
              yAxis: false,
              layout: 'vertical',
              label: {
                measure: {
                  position: 'middle',
                  style: {
                    fill: '#fff',
                  },
                },
              },
              // 自定义 legend
              
            });           
            bulletPlot.render();
        },
    handleSubmit() {
      if (!this.value||this.value==null) {//用户的admin为0
        this.openNotification('NOK','发送信息错误','请勿发送空信息!')
        return;
      }
      this.insertSentence({username:this.account.username,admin:0,content:this.value}).then((res)=>{
        this.updateTalkList()
        //  console.log(res)
      },(error)=>{
        this.openNotification('NOK','发送信息失败','服务器开了会儿小差,请重新发送!')
      })
      this.submitting = true;

      setTimeout(() => {
        this.submitting = false;
        this.comments = [
          {
            author: 'Han Solo',
            avatar: 'https://zos.alipayobjects.com/rmsportal/ODTLcjxAfvqbxHnVXCYX.png',
            content: this.value,
            datetime: moment().fromNow(),
          },
          ...this.comments,
        ];
        this.value = '';
      }, 1000);
    },
    handleChange(e) {
      this.value = e.target.value;
    },
     toggleCollapsed() {
      this.collapsed = !this.collapsed;
    },
    updateTalkList() {
      if(!this.signIn || this.account === null) {
        return
      }
      this.getTalkList(this.account.username).then((res) => {
      let i = 0
      this.sentenceList.length = 0
      for(let item of res){
          item.key = i++
          this.sentenceList.push(item);
      }
      this.$nextTick(function(){
        let div = this.$refs.sentencePart
        div.scrollTop = div.scrollHeight
      })
      this.finishUpdate()
      }, (error) => {
        this.openNotification('NOK','获取对话记录失败','服务器开了会儿小差,请刷新重试!')
      })
    },
    openNotification(type,title,msg) {
      let iconType = ''
      let iconColor = ''
      if(type=='OK'){
        iconType = 'smile'
        iconColor = '#52c41a'
      }
      else
      {
        iconType = 'frown'
        iconColor = '#eb2f96'
      }
      this.$notification.open({
        message: title,
        description: msg,
        icon: h => h('a-icon', {
          props: {
            type: iconType,
            theme: 'twoTone',
            'two-tone-color': iconColor
          }
        }),
      });
    }
    },
    mounted(){
      if(this.signIn==false&&this.account==null)
      {
        this.loginName='登录'
      }
      else{
        this.loginName='登出'
      }
        this.humiPaint();
        this.tempPaint();
        this.finishUpdate()
    }
    
}
</script>

<style lang="scss" scoped>
.aButton{ 
  color: #efe7db !important;
  border-radius: 8px;
  border: 3px solid #efe7db;
  cursor: pointer;
  transition: all 0.2s cubic-bezier(0.55, 0.085, 0.68, 0.53);
  top:1px;
  left:50px;
  background-color:rgba(89,242,130, 0.78);
}
i{
    width:35px;
    height:35px;
    font-size:25px;
    padding: 10px;
    margin-left: 2%;
}
h3{
    color: #fefefe;
    padding: 10px;
    margin: 0;
}
.stuPage{
    width:360px;
    height: 780px;
    margin-left: 38%;
    margin-top: 0.5%;
    display: block;
    border: 2px solid grey;
    background: black;
    border-radius: 15px;
    padding: 3px;
    padding-top: 5px;
    .toolsBar{
        background-color: #2a2f55;
        box-shadow: 0 0 2px 0 #121633;
        border: 1px solid grey;
        border-bottom: 0;
        border-radius: 10px 10px 0 0 ;
        width: 100%;
        height: 6%;
        display: flex;
    }
    .dataPart{
        width: 100%;
        height: 94%;
        background-color: #191e3f;
        border: 1px solid grey;
        border-top: 0;
        border-radius:  0 0 10px 10px;
        overflow-y:scroll;
        display: inline-block;
        .myCard{
            background-color: #2a2f55;
            box-shadow: 0 0 2px 0 #121633;
            width: 48%;
            height: 220px;
            margin: 3px;
            float: left;
            display: flex;
        }
    }    
}

.talkPart{
    width:167px;
    height: 219px;
    .sentencePart{
      width:100%;
      height: 130px;
      border-bottom: 1px solid rgba(255,255,255,0.2);
      background-color: rgba(255, 255, 255, 0.062);
      overflow-y: scroll;
      overflow-x: hidden;
    }
    .sendPart{
      width:100%;
      height:50px;
    }
}

table{
  width: 100%;
  display: block;
  padding-left: 1%;
  padding-right: 1%;
  padding-top:4px;
  tr{
    width: 100%;
    margin-top: 1%;
    display: flex;
    td{
      width: 50%;
      h1.type1{
        width: auto;
        padding-left: 18px;
        padding-right: 18px;
        padding-top: 5px;
        padding-bottom: 5px;
        height: auto;
        border-radius: 10px;
        background-color: rgba(89,242,130, 0.78);
        color: rgba(255, 255, 255, 1);
        font-size: 16px;
        text-align: left;
        font-family: Roboto;
        border: 1px solid rgba(255, 255, 255, 1);
        word-break:break-all; 
        float: right;
      }
      h1.type2{
        width: auto;
        padding-left: 18px;
        padding-right: 18px;
        padding-top: 5px;
        padding-bottom: 5px;
        height: auto;
        border-radius: 10px;
        background-color: rgba(255, 255, 255, 1);
        color: rgba(89,242,130, 0.78);
        font-size: 16px;
        text-align: left;
        font-family: Roboto;
        border: 1px solid rgba(89,242,130, 0.78);
        word-break:break-all; 
        float: left;
      }
      
    }
  }
}
.message {
  width: 400px;
  height: 200px;
  line-height: 200px;
  text-align: center;
  font-size: 1.1rem;
  .login {
    display: inline-block;
    width: 80px;
    color: #507e64;
    height: 50px;
  }
}
::-webkit-scrollbar
{
	width: 0px;
}


</style>